﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Windows.Forms;
using System.Text;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using Fcdbas.WinUI.Forms;
using Fcdbas.WinUI.Common;
using Fcdbas.Platform.Properties;
using Fcdbas.Biz;
using Fcdbas.WinUI.Controls;
using DevExpress.XtraGrid.Columns;
namespace Fcdbas.WinUI.Forms
{
    public partial class frmQuery : BaseForm
    {
        internal static readonly string Field_Separator = "(*^)";
        internal static readonly string Record_Separator = "(&^)";
        private string userWhere;
        private List<fnd_user_profile> QProfile;
        private Control gCtrl = null;
        private int Mode;
        public frmQuery()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="form"></param>
        /// <param name="pProfile"></param>
        /// <param name="mode">是否需要抽取数据，0抽取，1不抽取</param>
        /// <param name="where">附加的查询条件</param>
        public frmQuery(BaseForm form,List<fnd_user_profile> pProfile,int mode=0,string where="",Control ctrl=null)
        {
            InitializeComponent();
            this.ListFrom = form;
            this.gCtrl = ctrl;
            QProfile = pProfile;
            userWhere = where;
            InitFields();
            InitQuery();
            RegisterAccelerator(this.btnOK, Keys.Enter);
            RegisterAccelerator(this.btnCancel, Keys.Escape);
            RegisterAccelerator(this.btnClear, Keys.F4);
            Mode = mode;
          //  cGridControl1.Focus();
          //  gridView1.Focus();
            

            //gridView1.FocusedColumn = gridView1.Columns[2];
            
           // gridView1.set = 1;
            //RegisterAccelerator(this.btnSave, Keys.ControlKey | Keys.S);
        }


        


        public BaseForm ListFrom
        {
            get;
            set;
        }
        /// <summary>
        /// 当前查询对象
        /// </summary>
        public string Entity
        {
            get;
            set;
        }

        public string Where
        {
            get
            {
                 string where = userWhere;
                if (!string.IsNullOrEmpty(where) && !string.IsNullOrEmpty(this.cMemoEdit1.Text))
                    where = userWhere + " and " + this.cMemoEdit1.Text;
                else if (!string.IsNullOrEmpty(this.cMemoEdit1.Text))
                    where = this.cMemoEdit1.Text;
                return where;
            }
        }
        public string OrderBy
        {
            get
            {
                return cMemoEdit2.Text; 
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public Query DataQuery
        {
            get;
            set;
        }


        public IList<QueryItem> QueryDataSource
        {
            get;
            set;
        }


        /// <summary>
        /// 初始化查询
        /// </summary>
        void InitQuery()
        {
            DataQuery = new Query();
           // QueryDataSource = new List<QueryItem>();
           // DataQuery.QueryItems = QueryDataSource;
         //   this.bsQueryItem.DataSource = new List<QueryItem>();
            this.leQuery.Properties.DataSource = QProfile;
            leQuery.EditValue = "上次查询";
           // this.leQuery.Properties.s
        }

        private Dictionary<string, string> ParseColumnValue(string attValue)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            if (string.IsNullOrEmpty(attValue))
                return dic;
            string[] fields = attValue.Split(Record_Separator);
            foreach (string field in fields)
            {
                string[] vals = field.Split(Field_Separator);
                if (vals == null || vals.Length != 2)
                {
                    return dic;
                }
                dic.Add(vals[0], vals[1]);
            }
            return dic;
        }
        

        /// <summary>
        /// 初始化字段
        /// </summary>
        void InitFields()
        {
           // var gv = (this.ListFrom as BaseListForm).GV;
            List<DataItem> columns = this.ListFrom.CurrentSourceBinding.Columns;
            if (columns == null)
                return;
            IList<FieldItem> fieldlist = new List<FieldItem>();
            IList<FieldItem> sumList = new List<FieldItem>();
            IList<QueryItem> qList =  new List<QueryItem>();
            List<GridColumn> gcList = new List<GridColumn>();
            if (gCtrl != null && gCtrl is cGridControl )
            {
                GridView gv = ((cGridControl)gCtrl).MainView as GridView;
                foreach (GridColumn gc in gv.Columns)
                    gcList.Add(gc);
            }
//            for (int index = 0;index<gv.Columns.Count;index++)
            int idx = 0; 
            foreach(DataItem di in columns)
            {
                if (!di.OnlyInWhereClause)
                    continue;
                FieldItem fi = new FieldItem();
                fi.FieldCaption = string.IsNullOrEmpty(di.Caption) ? di.ColumnName:di.Caption;
                fi.FieldName = di.ColumnName;
                if(di.DataType != null)
                    fi.DataType = di.DataType.Name;
                fieldlist.Add(fi);
                sumList.Add(fi);
                
                QueryItem qi = new QueryItem();
                qi.DataType = di.DataType;
                qi.WithOr = " and ";
                if (!string.IsNullOrEmpty(di.RefFunction))
                    qi.FieldName = di.RefFunction;
                else
                    qi.FieldName = di.ColumnName;
                qi.Caption = string.IsNullOrEmpty(di.Caption) ? di.ColumnName : di.Caption;
                if (gCtrl != null && gCtrl is cGridControl)
                {
                    GridColumn gc = gcList.Find(p => p.FieldName == qi.FieldName);
                    if (gc == null)
                        gc = gcList.Find(p => p.Caption == qi.Caption);
                    if (gc != null)
                        qi.OrderIndex = gc.VisibleIndex;
                    if (gc == null || gc.Visible== false)
                        continue;
                }
                else
                    qi.OrderIndex = idx;
                idx++;
                qList.Add(qi);
            }

           // lpFields.DataSource = fieldlist;
            bsQuerySum.DataSource = sumList;
            bsQueryItem.DataSource = qList.OrderBy(p => p.OrderIndex).ToList();
        }


        /// <summary>
        /// 获取历史查询
        /// </summary>
        void GetHistoryQuery()
        {

        }
        private static readonly string Operations = ",%,!,>,<,>=,<=,!=,..,;";

        private void cButton1_Click(object sender, System.EventArgs e)
        {
            if (this.bsQueryItem.DataSource == null)
            {
                return;
            }
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
          //  this.cMemoEdit1.EditValue = this.DataQuery.ConditionBuilder(this.bsQueryItem.DataSource   as IList<QueryItem>,this.chkcase.Checked);
           // if(string.IsNullOrEmpty(cMemoEdit1.Text) && string.IsNullOrEmpty(cMemoEdit2.Text))
          //      return ;
            //if (!string.IsNullOrEmpty(cMemoEdit1.Text))
            //{
            //    if (string.IsNullOrEmpty(this.ListFrom.CurrentSourceBinding.DefaultWhere))
            //        this.ListFrom.CurrentSourceBinding.UserWhere = this.cMemoEdit1.Text;
               
            //}
            string where = userWhere;
            if (!string.IsNullOrEmpty(where) && !string.IsNullOrEmpty(this.cMemoEdit1.Text))
                where = userWhere + " and " + this.cMemoEdit1.Text;
            else if (!string.IsNullOrEmpty(this.cMemoEdit1.Text))
                where = this.cMemoEdit1.Text;
            this.ListFrom.CurrentSourceBinding.UserWhere = where;
            this.ListFrom.CurrentSourceBinding.UserOrderBy = cMemoEdit2.Text;
           
            //if (!string.IsNullOrEmpty(cMemoEdit2.Text))
            //{
            //    this.ListFrom.CurrentSourceBinding.UserOrderBy = cMemoEdit2.Text;
            
            //}
            if (Mode == 0 && this.ListFrom.CurrentSourceBinding.OnDataIsQuerying(this))
                this.ListFrom.UserQuery(DataSourcePopulate.RePopulate);
            //this.ListFrom.CurrentSourceBinding.ResetBindings(false);
            //this.ListFrom.MasterdataSourceBinding.DefaultWhere = this.cMemoEdit1.EditValue.ToString();
            //this.ListFrom.MasterdataSourceBinding.vrtDataSourceRefresh(1);
            //this.ListFrom.MasterdataSourceBinding.ResetBindings(false);
            SaveProfile("上次查询",true);
            this.Close();
            //(this.ListFrom as cTableWindow).Query(this.cMemoEdit1.EditValue.ToString());
           // frmQuaryResult qResult = new frmQuaryResult(this.ListFrom.MasterdataSourceBinding, this.cMemoEdit1.EditValue.ToString());
          //  qResult.Show();
        }

        private void gridView1_ColumnChanged(object sender, System.EventArgs e)
        {

        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (this.bsQueryItem.DataSource == null)
            {
                return;
            }
            if (e.Column.FieldName == "OrderBy")
            {
                QueryItem qi = this.bsQueryItem.Current as QueryItem;
                qi.OrderSeq = 0;
                if (qi != null )
                {
                    if (e.Value == null || string.IsNullOrEmpty(e.Value.ToString()))
                    {
                        qi.OrderSeq = null;
                    }
                    else
                    {
                        List<QueryItem> list = this.bsQueryItem.DataSource as List<QueryItem>;
                        int? max = (from q in list
                                    where q.OrderSeq != null
                                    select q.OrderSeq).Max();
                        qi.OrderSeq = max + 1;
                    }
                }
            }
            this.cMemoEdit1.EditValue = this.DataQuery.ConditionBuilder(this.bsQueryItem.DataSource as IList<QueryItem>,chkcase.Checked);
            this.cMemoEdit2.EditValue = this.DataQuery.OrderByBuilder(this.bsQueryItem.DataSource as List<QueryItem>);
        }

        private void btnClear_Click(object sender, System.EventArgs e)
        {
            InitQuery();
            InitFields();
            SetGridFocus();
        }
        public string UserWhere
        {
            get
            {
                return this.DataQuery.ConditionBuilder(this.bsQueryItem.DataSource as IList<QueryItem>, chkcase.Checked);
            }
        }
        private void btnCancel_Click(object sender, System.EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }
        private fnd_user_profile CreateQuery()
        {
            fnd_user_profile f = new fnd_user_profile();
            f.pres_object = this.ListFrom.GetType().FullName;
            f.identity = AppEnvironment.Session.USER_ID;
            f.type_flag = "Q";
            f.Status = Core.RecordStatus.New;
            f.data_source = ListFrom.CurrentSourceBinding.Name;
            return f;
        }
        private void btnSave_Click(object sender, System.EventArgs e)
        {
            dlgQuerySave dlg = new dlgQuerySave();
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                SaveProfile(dlg.QueryName,false);
            }
        }
        private void SaveProfile(string queryName,bool IsOnlyLocal)
        {
            bool find = true;
            fnd_user_profile qi = QProfile.Find(p => p.description == queryName);
            if (qi == null)
            {
                qi = CreateQuery();
                find = false;
            }
            else
                qi.Status = Core.RecordStatus.Edit;
            qi.description = queryName;
            qi.info = GetAttributeValue();
            qi.where_clause = this.DataQuery.ConditionBuilder(this.bsQueryItem.DataSource as IList<QueryItem>, chkcase.Checked);
            qi.order_clause = cMemoEdit2.Text;
            if (!find)
                QProfile.Add(qi);
            ListFrom.SaveUserQueryfile(qi,IsOnlyLocal);
            leQuery.EditValue = queryName;
        }
        private string GetAttributeValue()
        {
            List<QueryItem> list = bsQueryItem.DataSource as List<QueryItem>;
            if (list == null)
                return "";
            StringBuilder sb = new StringBuilder();
            foreach (QueryItem qi in list)
            {
                if (qi.Value != null && !string.IsNullOrEmpty(qi.Value.ToString()))
                {
                    sb.Append(qi.FieldName);
                    sb.Append(Field_Separator);
                    sb.Append(qi.Value.ToString());
                    sb.Append(Record_Separator);
                }
            }
            return sb.ToString();
        }
        private void chkcase_CheckedChanged(object sender, System.EventArgs e)
        {
            this.cMemoEdit1.EditValue = this.DataQuery.ConditionBuilder(this.bsQueryItem.DataSource as IList<QueryItem>, chkcase.Checked);
        }

        private void leQuery_EditValueChanged(object sender, EventArgs e)
        {
            if(QProfile == null )
                return;
            fnd_user_profile qi = QProfile.Find(p => p.description == leQuery.EditValue.ToString() );
            if (qi != null)
            {
                Dictionary<string, string> dic = ParseColumnValue(qi.info);
                List<QueryItem> list = bsQueryItem.DataSource as List<QueryItem>;
                for (int i = 0; i < list.Count; i++)
                {
                    if(dic.Keys.Contains(list[i].FieldName))
                        list[i].Value = dic[list[i].FieldName];
                    else
                        list[i].Value = "";
                }
                bsQueryItem.DataSource = list;
                cMemoEdit1.Text = qi.where_clause;
                cMemoEdit2.Text = qi.order_clause;
                this.cGridControl1.RefreshDataSource();
            }
        }
        private void SetGridFocus()
        {
            this.tabQuery.Focus();
            pageQuerySetting.Focus();
            //this.tabQuery.TabPages[0].Focus();
            this.cGridControl1.Focus();
            if (gridView1.Columns.Count > 0 && gridView1.RowCount > 0)
            {
                gridView1.Focus();
                gridView1.FocusedRowHandle = 0;
                gridView1.FocusedColumn = gridView1.Columns[2];

                gridView1.SelectCell(0, gridView1.Columns[2]);
                gridView1.ShowEditorByMouse();
            }
        }
        private void frmQuery_Load(object sender, EventArgs e)
        {
            
        }

        private void frmQuery_Activated(object sender, EventArgs e)
        {
            SetGridFocus();
        }



    }

    sealed class FieldItem
    {
        public string FieldName
        {
            get;
            set;
        }

        public string FieldCaption
        {
            get;
            set;
        }

        public string Group
        {
            get;
            set;
        }

        public string DataType
        {
            get;
            set;
        }
    }
}
